<template>
  <div id="userRegisterPage">
    <h2 class="title">{{ APP_TITLE }}</h2>
    <div class="desc">{{ APP_DESCRIPTION }}</div>
    <a-form
      ref="formRef"
      name="custom-validation"
      :model="formState"
      :rules="rules"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item name="userAccount">
        <a-input
          v-model:value="formState.userAccount"
          placeholder="请输入用户账号!"
          autocomplete="username"
        >
          <template #prefix>
            <UserOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item name="userPassword" :rules="rules.userPassword">
        <a-input-password
          v-model:value="formState.userPassword"
          placeholder="请输入用户密码"
          autocomplete="new-password"
        >
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item name="checkPassword" :rules="rules.checkPassword">
        <a-input-password
          v-model:value="formState.checkPassword"
          placeholder="请再次输入密码"
          autocomplete="new-password"
        >
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <!-- 如果需要邀请码 -->
      <a-form-item v-if="showInviteCode" name="inviteCode">
        <a-input v-model:value="formState.inviteCode" placeholder="请输入邀请码">
          <template #prefix>
            <KeyOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>

      <div class="tips">已有账号？<RouterLink to="/login">去登录</RouterLink></div>
      <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button
          :loading="loading"
          :disabled="disabled"
          type="primary"
          html-type="submit"
          style="width: 100%"
        >
          注册
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { LockOutlined, UserOutlined, KeyOutlined } from '@ant-design/icons-vue'
import { userRegisterUsingPost } from '@/api/userController'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { APP_DESCRIPTION, APP_TITLE } from '@/config/global'

interface FormState {
  userAccount: string
  userPassword: string
  checkPassword: string
  inviteCode?: string // 如果需要邀请码
}

const formRef = ref<any>(null)
const formState = reactive<FormState>({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  inviteCode: undefined,
})

// 验证规则
const validatePass = async (_rule: any, value: string) => {
  if (value === '') {
    return Promise.reject('请输入用户密码')
  } else {
    if (formState.checkPassword !== '') {
      formRef.value.validateFields(['checkPassword'])
    }
    return Promise.resolve()
  }
}

const validatePass2 = async (_rule: any, value: string) => {
  if (value === '') {
    return Promise.reject('请再次输入密码')
  } else if (value !== formState.userPassword) {
    return Promise.reject('两次输入的密码不一致')
  } else {
    return Promise.resolve()
  }
}

const rules = {
  userAccount: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_-]{4,16}$/,
      message: '用户账号必须包含字母、数字、下划线、减号，长度在4到16位之间',
      trigger: 'blur',
    },
  ],
  userPassword: [
    { required: true, validator: validatePass, trigger: 'blur' },
    // {
    //   pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$/,
    //   message: '密码必须包含大小写字母、数字和特殊字符，长度在8到16位之间',
    //   trigger: 'blur',
    // },
  ],
  checkPassword: [{ validator: validatePass2, trigger: 'blur' }],
}

const loading = ref(false)
const showInviteCode = ref(true) // 控制邀请码字段的显示

const router = useRouter()

const onFinish = async (values: any) => {
  try {
    loading.value = true
    const res = await userRegisterUsingPost(values)
    console.log(res)
    if (res.code === 0 || res.code === 200) {
      await router.push({
        path: '/login',
        replace: true, // 确保导航后不会留下历史记录
      })
      message.success('注册成功')
    } else {
      message.error(`注册失败: ${res.message}`)
    }
  } catch (error) {
    message.error(`注册异常: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}

const disabled = computed(() => {
  return !(formState.userAccount && formState.userPassword && formState.checkPassword)
})
</script>

<style scoped>
#userRegisterPage {
  max-width: 360px;
  margin: 0 auto;
  padding: 24px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fff;
}

.title {
  text-align: center;
  margin-bottom: 16px;
  font-size: 24px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 24px;
}

.tips {
  margin-bottom: 16px;
  text-align: right;
  font-size: 13px;
}

.site-form-item-icon {
  color: rgba(0, 0, 0, 0.25);
}
</style>
